//
//  YXHTTPRequst.m
//  JS_Block&Networking
//
//  Created by 向乾操 on 16/2/29.
//  Copyright © 2016年 向乾操. All rights reserved.
//

#import "YXHTTPRequst.h"

@implementation YXHTTPRequst

+ (YXHTTPRequst *)shareInstance {
    static YXHTTPRequst * requst = nil;
    if (!requst) {
        requst = [[YXHTTPRequst alloc] init];
    }
    return requst;
}

- (void)networking:(NSString *)urlString
        parameters:(NSDictionary *)parame
            method:(YXRequstMethodType)TYPE
           success:(void (^) (NSDictionary *))success_
          failsure:(void (^) (NSError *))failsure_ {
    //得到一个url
    NSURL * url = [NSURL URLWithString:urlString];
    //初始化一个requst对象
    NSMutableURLRequest * requst = [[NSMutableURLRequest alloc] initWithURL:url];
    //配置requst对象
    if (TYPE == 1) {
        requst.HTTPMethod = @"POST";
        requst.HTTPBody = [self appendingWithParameters:parame];
    }else {
        NSAssert(!parame, @"您当前使用的是GET请求，请直接把参数拼接在urlString中，您可以使用本类的“method1”方法完成urlString的拼接！");
        requst.HTTPMethod = @"GET";
    }
    requst.timeoutInterval = 60;
    //session来做网络请求，并且回执到主线程中执行回调block
    NSURLSession * session = [NSURLSession sharedSession];
    [[session dataTaskWithRequest:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data && !error && success_) {
                NSError * error = nil;
                id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                success_(obj);
            }else if (error && !data && failsure_) {
                failsure_(error);
            }
        });
    }] resume];
}
- (NSData *)appendingWithParameters:(NSDictionary *)parame {
    NSMutableString * retValue = [NSMutableString string];
    for (NSString * key in parame.allKeys) {
        NSString * value = parame[key];
        [retValue appendFormat:@"%@=%@&",key,value];
    }
    return [retValue dataUsingEncoding:NSUTF8StringEncoding];
}

@end







